import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.net.URL;
import java.util.LinkedList;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.omg.CORBA.Current;

public class MainScreen extends JPanel implements Runnable {// 게임 실행 관리하는 주 쓰레드
															// 구현

	// Image : 일반적인 이미지를 관리하는 클래스
	// 보통 초기에 로딩해서 실행중에 재사용 하는 방식으로 처리
	Image backImage, playerImage, playerImage2, stoneImage, missileImage, missileImage2, explosionImage,
			enemy1Image, enemy2Image, enemy3Image, bullet1Image, bullet2Image,
			P1LifeImage2, P1LifeImage1, P2LifeImage2, P2LifeImage1, bossImage, bossBulletImage, bossBulletImage2,
			ExplosionL1, ExplosionL2, playerExplosion, bossFlicker;
	
	Background background;
	Player player;
	Player2 player2;
	Boss boss;

	public static int enemy2x;
	public static int enemy2y;
	public static int enemy3x;
	public static int enemy3y;

	LinkedList<GameObject> stones = new LinkedList<GameObject>();

	LinkedList<GameObject> enemy1s = new LinkedList<GameObject>();
	LinkedList<GameObject> enemy2s = new LinkedList<GameObject>();
	LinkedList<GameObject> enemy3s = new LinkedList<GameObject>();

	// 플레이어 미사일
	LinkedList<GameObject> missiles = new LinkedList<GameObject>();
	LinkedList<GameObject> missiles2 = new LinkedList<GameObject>();

	// 적 탄알
	LinkedList<GameObject> bullet1s = new LinkedList<GameObject>();
	LinkedList<GameObject> bullet2s = new LinkedList<GameObject>();
	LinkedList<BossDanMaKu1>BossDanMaKu1arr = new LinkedList<BossDanMaKu1>();
	LinkedList<BossDanMaKu2> BossDanMaKu2arr = new LinkedList<BossDanMaKu2>();
	
	LinkedList<Explosion> explosions = new LinkedList<Explosion>();

	// Timer관련 변수 선언

	// (변수에 대입하는 값은 Timer라는 별도의 클래스에 public static으로 만들어 별도 관리)
	// (Timer 값은 저 한테 허락받고 변경하세요 !!! -두현-)
	long prevStoneCreationTime, prevEnemy1CreationTime, prevEnemy2CreationTime,
			prevEnemy3CreationTime;
	long prevFireTime, prevFireTime2;
	long prevBossMoveTime;
	long startTime;

	private final int STATUS_INIT = 1;
	private final int STATUS_RUNNING = 2;
	private final int STATUS_PAUSE = 3;
	private final int STATUS_CLEAR = 4;
	private final int STATUS_FAIL = 5;

	// 현재 게임 상태
	private int status = STATUS_RUNNING;
	
	private boolean runpause = true;

	public long shootdownTime = 0;
	
	//충돌 측정 사각형 선언
	Rectangle rect1, rect2;

	// 점수
	private int score, score2;

	// 폰트 설정
	private Font gameoverFont, scoreFont, pauseFont;

	private Clip BGMplayer, bossbgmplayer, attackplayer,brokeplayer,damageplayer;
	
	AudioInputStream BGM, bossbgm, attackSound, brokeSound, damageSound ;
	
	

	public MainScreen() {
		startTime = System.currentTimeMillis();
		init();
	}

	private void init() {
		// 이미지 파일을 읽는 코드에서 예외가 발생할 수 있기 때문에 예외 처리
		try {
			// getClass().getResource() : 소스파일(클래스파일)이 있는 위치에서 파일을 찾는 기능
			// URL : 유니폼 리소스 로케이션, 자원(파일)의 위치를 표시하는 클래스,
			URL url = getClass().getResource("background.png");
			// ImageIO.read(url) : 지정된 경로에 있는 이미지파일을 읽어서 이미지 객체로 반환
			backImage = ImageIO.read(url);			
			
			url = getClass().getResource("P11.png");
			playerImage = ImageIO.read(url);

			url = getClass().getResource("P22.png");
			playerImage2 = ImageIO.read(url);

			url = getClass().getResource("stone.png");
			stoneImage = ImageIO.read(url);

			url = getClass().getResource("greenLaserRay1.png");
			missileImage = ImageIO.read(url);
			
			url = getClass().getResource("redLaserRay2.png");
			missileImage2 = ImageIO.read(url);

			url = getClass().getResource("explosion.png");
			explosionImage = ImageIO.read(url);

			url = getClass().getResource("Enemy1.png");
			enemy1Image = ImageIO.read(url);

			url = getClass().getResource("Enemy22.png");
			enemy2Image = ImageIO.read(url);

			url = getClass().getResource("Enemy33.png");
			enemy3Image = ImageIO.read(url);

			url = getClass().getResource("bullet1.png");
			bullet1Image = ImageIO.read(url);

			url = getClass().getResource("bullet2.png");
			bullet2Image = ImageIO.read(url);

			url = getClass().getResource("P1Life2.png");
			P1LifeImage2 = ImageIO.read(url);

			url = getClass().getResource("P1Life1.png");
			P1LifeImage1 = ImageIO.read(url);

			url = getClass().getResource("P2Life2.png");
			P2LifeImage2 = ImageIO.read(url);

			url = getClass().getResource("P2Life1.png");
			P2LifeImage1 = ImageIO.read(url);

			url = getClass().getResource("boss.png");
			bossImage = ImageIO.read(url);
			url = getClass().getResource("bossdanmaku.png");
			bossBulletImage = ImageIO.read(url);
			url = getClass().getResource("bossdanmaku2.png");
			bossBulletImage2 = ImageIO.read(url);
			
			url = getClass().getResource("ExplosionL1.png");
			ExplosionL1 = ImageIO.read(url);
			
			url = getClass().getResource("ExplosionL2.png");
			ExplosionL2 = ImageIO.read(url);
			
			url = getClass().getResource("PlayerExplosion.png");
			playerExplosion = ImageIO.read(url);
			
			url = getClass().getResource("boss.png");
			bossFlicker = ImageIO.read(url);
			
			url = getClass().getResource("BGM.wav");
			BGM = AudioSystem.getAudioInputStream(url);//오디오파일에 대한 스트림
			BGMplayer = AudioSystem.getClip();//오디오 재생기 생성
			BGMplayer.open(BGM);//오디오 재생기에 오디오 음원을 삽입
			BGMplayer.loop(Clip.LOOP_CONTINUOUSLY);
			BGMplayer.start();
			
			url = getClass().getResource("boss.wav");
			bossbgm = AudioSystem.getAudioInputStream(url);//오디오파일에 대한 스트림
			bossbgmplayer = AudioSystem.getClip();//오디오 재생기 생성
			bossbgmplayer.open(bossbgm);//오디오 재생기에 오디오 음원을 삽입
			//bgm.stop();
			
			
			
			
			url = getClass().getResource("laser.wav");
			attackSound = AudioSystem.getAudioInputStream(url);
			attackplayer = AudioSystem.getClip();
			attackplayer.open(attackSound);
			attackplayer.loop(1);
			attackplayer.stop();
			
			
			url = getClass().getResource("220062__klangfabrik__explosion004.wav");
			damageSound = AudioSystem.getAudioInputStream(url);
			damageplayer = AudioSystem.getClip();
			damageplayer.open(damageSound);
			damageplayer.loop(1);
			damageplayer.stop();
			
			url = getClass().getResource("127951__omar-alvarado__blast.wav");
			brokeSound = AudioSystem.getAudioInputStream(url);
			brokeplayer = AudioSystem.getClip();
			brokeplayer.open(brokeSound);
			brokeplayer.loop(1);	
			brokeplayer.stop();

			

			// 폰트 설정
			gameoverFont = new Font("Verdana", Font.BOLD, 15);
			scoreFont = new Font("Verdana", Font.BOLD, 15);
			pauseFont = new Font("Verdana", Font.BOLD, 15);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		background = new Background(backImage);
		player = new Player(playerImage, P1LifeImage1, P1LifeImage2);
		player2 = new Player2(playerImage2, P2LifeImage1, P2LifeImage2);
		boss = new Boss(bossImage,1000,200,4);

		setBackground(Color.black);
		// Panel에 KeyBoard 이벤트 수신기 등록
		this.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				
				

				super.keyPressed(e);
				player.keyPressedHandler(e);
				player2.keyPressedHandler(e);
				if (e.getKeyCode() == KeyEvent.VK_P) {
					runpause = !(runpause);
					if ((runpause)) {
						status = STATUS_RUNNING;
					} else {
						status = STATUS_PAUSE;
					}
				}

			}

			@Override
			public void keyReleased(KeyEvent e) {

				super.keyReleased(e);
				player.keyReleasedHandler(e);
				player2.keyReleasedHandler(e);
			}
		});

		Thread thread = new Thread(this);
		thread.start(); // -> run 호출

	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		background.render(g);
		player.render(g);// 개별적인 정보들은 그것을 가지고 있는 애가 처리해라
		player2.render(g);
		boss.render(g);

		for (GameObject enemy1 : enemy1s) {
			enemy1.render(g);
		}
		for (GameObject enemy2 : enemy2s) {
			enemy2.render(g);
		}
		for (GameObject enemy3 : enemy3s) {
			enemy3.render(g);
		}
		for (GameObject stone : stones) {
			stone.render(g);
		}
		for (GameObject missile : missiles) {
			missile.render(g);
		}
		for (GameObject missile : missiles2) {
			missile.render(g);
		}
		for (GameObject bullet1 : bullet1s) {
			bullet1.render(g);
		}
		for (GameObject bullet2 : bullet2s) {
			bullet2.render(g);
		}
		for(BossDanMaKu1 bossDanMaKu1 : BossDanMaKu1arr){
			bossDanMaKu1.render(g);
		}
		for(BossDanMaKu2 bossDanMaKu2 : BossDanMaKu2arr){
			bossDanMaKu2.render(g);
		}
		for (Explosion explosion : explosions) {
			explosion.render(g);
		}

		g.setFont(scoreFont);
		g.setColor(Color.red);
		g.drawString("SCORE = " + score, 600, 25);
		g.setColor(Color.blue);
		g.drawString("SCORE = " + score2, 600, 550);

		if (status == STATUS_FAIL) {
			g.setFont(gameoverFont);
			g.setColor(Color.orange);
			Rectangle2D rect = g.getFontMetrics().getStringBounds(
					"GAME OVER !!!", g);
			int x = (Constants.SCREEN_WIDTH - (int) rect.getWidth()) / 2;
			int y = (Constants.SCREEN_HEIGHT - (int) rect.getHeight()) / 2;
			g.drawString("GAME OVER !!!", x, y);
		}
		if (status == STATUS_PAUSE) {
			g.setFont(pauseFont);
			g.setColor(Color.white);
			Rectangle2D rect = g.getFontMetrics().getStringBounds("PAUSE", g);
			int x = (Constants.SCREEN_WIDTH - (int) rect.getWidth()) / 2;
			int y = (Constants.SCREEN_HEIGHT - (int) rect.getHeight()) / 2;
			g.drawString("PAUSE", x, y);
		}
	}

	@Override
	public void run() {

		while (true) {
			if (status == STATUS_PAUSE) {
				repaint();
				continue;
			}
			

			// 데이터 갱신
			long currentTime = System.currentTimeMillis();
			background.update();
			player.update();
			player2.update();

			if (!(player.active) && !(player2.active)) {
				status = STATUS_FAIL; // 비행기 둘다 터지면 겜오버
				if (shootdownTime == 0.0) {
					shootdownTime = System.currentTimeMillis();
					;
					// try{
					// bgm.open(Constants.gameover);
					// bgm.loop(Clip.LOOP_CONTINUOUSLY);
					// }catch(Exception ex){ex.printStackTrace();}
				}
				if (currentTime - shootdownTime > 5000) {
					BGMplayer.stop();
					bossbgmplayer.stop();
					MainPanel open = new MainPanel();
					Container frame = getParent();
					frame.add(open);
					frame.remove(this);
					frame.validate();
					frame.repaint();
					break;
				}
			}
			if(status == STATUS_CLEAR){
				BGMplayer.stop();
				bossbgmplayer.stop();
				ClearScreen clear = new ClearScreen();
				Container frame = getParent();
				frame.add(clear);
				frame.remove(this);
				frame.validate();
				frame.repaint();
				break;
			}

			showobject();

			crashcheck();

			makeobjeck();

			// 화면 출력
			repaint();

			try {
				Thread.sleep(30);
			} catch (Exception e) {
			}

		}

	}// run() end

	/**
	 * 돌, 미사일1,2, 적1, 적1공격, 폭발 표시
	 */
	private void showanddel(LinkedList<GameObject> objects){
		for (int i = objects.size() - 1; i >= 0; i--) {
			GameObject object = objects.get(i);
			object.update();
			if (object.active == false)
				objects.remove(object);
		}
	}
	private void showobject() {
		// for(Stone stone : stones){....}: 이 반복문 안에서는 목록 수정 불가능
		showanddel(enemy1s);
		showanddel(enemy2s);
		showanddel(enemy3s);
		showanddel(stones);
		showanddel(missiles);
		showanddel(missiles2);
		showanddel(bullet1s);

		
		for (int i = bullet2s.size() - 1; i >= 0; i--) {
			Bullet2 bullet2 = (Bullet2)bullet2s.get(i);
			if (bullet2.thetaControl == 0) {
				bullet2.theta = 270;
			} else if (bullet2.thetaControl == 1) {
				bullet2.theta = 300;
			} else if (bullet2.thetaControl == 2) {
				bullet2.theta = 330;
			} else if (bullet2.thetaControl == 3) {
				bullet2.theta = 0;
			} else if (bullet2.thetaControl == 4) {
				bullet2.theta = 30;
			} else if (bullet2.thetaControl == 5) {
				bullet2.theta = 60;
			} else if (bullet2.thetaControl > 5) {
				bullet2.thetaControl = 0;
			}
			bullet2.update();
			
			if (bullet2.active == false) // 이미 다지나간 미사일은 삭제
				bullet2s.remove(bullet2);
		}
		
		for (int i = explosions.size() - 1; i >= 0; i--) {
			explosions.get(i).update(); // 표시할 이미지 갯수만큼 카운트 증가 시킨다.
			if (explosions.get(i).active == false) {
				explosions.remove(i); // 번호로 제거
			}
		}

		boss.update();
		if (boss.x == boss.moveToX && boss.y == boss.moveToY) {
			boss.moveBoss();
		}
		for (int i = BossDanMaKu1arr.size() - 1; i >= 0; i--) {
			BossDanMaKu1arr.get(i).update(); // 표시할 이미지 갯수만큼 카운트 증가 시킨다.
			if (BossDanMaKu1arr.get(i).active == false) {
				BossDanMaKu1arr.remove(i); // 번호로 제거
			}
		}
		for (int i = BossDanMaKu2arr.size() - 1; i >= 0; i--) {
			BossDanMaKu2arr.get(i).update(); // 표시할 이미지 갯수만큼 카운트 증가 시킨다. 
			if (BossDanMaKu2arr.get(i).active == false) {
				BossDanMaKu2arr.remove(i); // 번호로 제거
			}
		}

	}

	/**
	 * 충돌 체크 메서드
	 */
	// 폭발 객체 생성 메서드
	private void blasting(Rectangle rect2,Image explosionImage,int n) {
		Explosion exp = new Explosion(explosionImage, rect2.x + rect2.width
				- explosionImage.getWidth(null) / 12, rect2.y
				+ (rect2.height - explosionImage.getHeight(null)) / 2, n);
		// 충돌지점 중앙이므로 미사일 맨끝에서 연기반을 뺀다
		explosions.add(exp);
	}
	
	//(부딪히는 객체 1,부딪히는 객체 2, 플레이어 스코어, 점수) 플레이어 미사일과 돌 및 미사일과 bullet1
	//점수 반환
	private int intercheck1(LinkedList<GameObject> objects1,LinkedList<GameObject> objects2,
			int jumsu ){
		int scoresum=0;
		for (int i = objects1.size() - 1; i >= 0; i--) {
			for (int j = objects2.size() - 1; j >= 0; j--) {
				Rectangle rect1 = objects2.get(j).getArea();
				Rectangle rect2 = objects1.get(i).getArea();

				if (rect1.intersects(rect2)) {
					// 폭발 객체 생성
					if(objects1.get(i).image.equals(missileImage))
						blasting(rect2,ExplosionL1,8);
					else if(objects1.get(i).image.equals(missileImage2))
						blasting(rect2,ExplosionL2,8);
					
					objects2.get(j).active = false;
					objects2.remove(j);

					objects1.get(i).active = false;
					objects1.remove(i);
					
					brokeplayer.setFramePosition(0);
					brokeplayer.start();

					
					// 50점 plus
					scoresum += jumsu;
					break;
				}
			}
		}
		return scoresum;
	}
	//(부딪히는 객체 1,부딪히는 객체 2, 플레이어 스코어, 점수, 데미지숫자) 플레이어 미사일과 적 1,2,3
	//점수반환
	private int intercheck2(LinkedList<GameObject> objects1,LinkedList<GameObject> objects2,
			int jumsu ,int damnum){
		int scoresum=0;
		for (int i = objects1.size() - 1; i >= 0; i--) {
			for (int j = objects2.size() - 1; j >= 0; j--) {
				Rectangle rect1 = objects2.get(j).getArea();
				Rectangle rect2 = objects1.get(i).getArea();

				if (rect1.intersects(rect2)) {
					if (objects2.get(j).damageCount < damnum) {
						objects2.get(j).damageCount++;
						objects1.get(i).active = false;
						objects1.remove(i);

						// 폭발 객체 생성
						blasting(rect2,explosionImage,6);
						damageplayer.setFramePosition(0);
						damageplayer.start();
						
						break;
					} else {
						// 폭발 객체 생성
						if(objects1.get(i).image.equals(missileImage))
							blasting(rect2,ExplosionL1,8);
						else if(objects1.get(i).image.equals(missileImage2))
							blasting(rect2,ExplosionL2,8);
						
						objects2.get(j).active = false;
						objects2.remove(j);

						objects1.get(i).active = false;
						objects1.remove(i);
						
						brokeplayer.setFramePosition(0);
						brokeplayer.start();
						
						// 50점 plus
						scoresum += jumsu;
						break;
					}
				}
			}
		}
		return scoresum;
	}
	//플레이어 가미가제(운석, 적 탄환, 적)
	private void intercheck3(LinkedList<GameObject> objects,GameObject playerwho){
		for (int j = objects.size() - 1; j >= 0; j--) {
			Rectangle rect1 = objects.get(j).getArea();
			Rectangle rect2 = playerwho.getArea();

			if (rect1.intersects(rect2)) {
				if (playerwho.damageCount == 0) {
					playerwho.damageCount++;
					objects.get(j).active = false;
					objects.remove(j);
					blasting(rect1,explosionImage,6);
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (playerwho.damageCount == 1) {
					playerwho.damageCount++;
					objects.get(j).active = false;
					objects.remove(j);
					blasting(rect1,explosionImage,6);
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (playerwho.damageCount >= 2) {
					objects.get(j).active = false;
					objects.remove(j);
					playerwho.active = false;
					blasting(rect1,explosionImage,6);
					blasting(rect2,playerExplosion,8);	
					
					brokeplayer.setFramePosition(0);
					brokeplayer.start();
					
					break;
				}
			}

		}
	}

	private void crashcheck() {
		// 플레이어1의 미사일에 돌 폭발
		score += intercheck1(missiles, stones, 50);
		// 플레이어1미사일과 bullet1
		score += intercheck1(missiles, bullet1s, 20);
		// 플레이어1의 미사일에 적1 폭발 (3번 맞아야 격추되도록 변경)
		score += intercheck2(missiles, enemy1s,100,1);
		// 플레이어1의 미사일에 적2 폭발
		score += intercheck2(missiles, enemy2s,100,3);
		// 플레이어1 미사일에 적3 폭발
		score += intercheck2(missiles, enemy3s,100,3);
		// player1의 미사일과 보스의 충돌 체크
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = missiles.size() - 1; i >= 0; i--) {
			Rectangle rect1 = boss.getArea();
			Rectangle rect2 = missiles.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (boss.hitPoint > 0) {
					boss.hitPoint--;
					missiles.get(i).active = false;
					missiles.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					boss.isHitMissile = true;
					score += 100;
					break;
				} else if (boss.hitPoint == 0) {
					boss.active = false;
					status = STATUS_CLEAR;
					bossbgmplayer.stop();
				}

			}
		}// /////////////////////////////////////////////////////////////boss 충돌
			// end
		// player2의 미사일과 보스의 충돌 체크
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = missiles2.size() - 1; i >= 0; i--) {
			Rectangle rect1 = boss.getArea();
			Rectangle rect2 = missiles2.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (boss.hitPoint > 0) {
					boss.hitPoint--;
					missiles2.get(i).active = false;
					missiles2.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					boss.isHitMissile = true;
					score2 += 100;
					break;
				} else if (boss.hitPoint == 0) {
					boss.active = false;
					status = STATUS_CLEAR;
					bossbgmplayer.stop();
				}
			}
		}// /////////////////////////////////////////////////////////////boss 충돌 end
		// player1과 보스 DanMaKu1과 충돌체
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = BossDanMaKu1arr.size() - 1; i >= 0; i--) {
			Rectangle rect1 = player.getArea();
			Rectangle rect2 = BossDanMaKu1arr.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (player.damageCount < 2) {
					player.damageCount++;
					BossDanMaKu1arr.get(i).active = false;
					BossDanMaKu1arr.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (player.damageCount >= 2) {
					player.active = false;
				}
			}
		}// /////////////////////////////////////////////////////////////boss 충돌 end
		// player2와 보스 DanMaKu1과 충돌체크
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = BossDanMaKu1arr.size() - 1; i >= 0; i--) {
			Rectangle rect1 = player2.getArea();
			Rectangle rect2 = BossDanMaKu1arr.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (player2.damageCount < 2) {
					player2.damageCount++;
					BossDanMaKu1arr.get(i).active = false;
					BossDanMaKu1arr.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (player2.damageCount >= 2) {
					player2.active = false;
				}
			}
		}// /////////////////////////////////////////////////////////////boss 충돌 end
		// player1과 보스 DanMaKu2와 충돌체크
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = BossDanMaKu2arr.size() - 1; i >= 0; i--) {
			Rectangle rect1 = player.getArea();
			Rectangle rect2 = BossDanMaKu2arr.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (player.damageCount < 2) {
					player.damageCount++;
					BossDanMaKu2arr.get(i).active = false;
					BossDanMaKu2arr.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (player.damageCount >= 2) {
					player.active = false;
				}
			}
		}// /////////////////////////////////////////////////////////////boss 충돌 end
		// player2와 보스 DanMaKu2와 충돌체
		// /////////////////////////////////////////////////////////////////boss
		// 충돌
		for (int i = BossDanMaKu2arr.size() - 1; i >= 0; i--) {
			Rectangle rect1 = player2.getArea();
			Rectangle rect2 = BossDanMaKu2arr.get(i).getArea();

			if (rect1.intersects(rect2)) {
				if (player2.damageCount < 2) {
					player2.damageCount++;
					BossDanMaKu2arr.get(i).active = false;
					BossDanMaKu2arr.remove(i);
					// 폭발 객체 생성
					blasting(rect2,explosionImage,6);
					
					damageplayer.setFramePosition(0);
					damageplayer.start();
					
					break;
				} else if (player2.damageCount >= 2) {
					player2.active = false;
				}
			}
		}// /////////////////////////////////////////////////////////////boss 충돌 end



		// 플레이어1 가미가제(운석)
		intercheck3(stones,player);

		// 플레이어1 가미가제(적1)
		intercheck3(enemy1s,player);
		
		// 플레이어1 가미가제(적2)
		intercheck3(enemy2s,player);

		// 플레이어1 가미가제(적3)
		intercheck3(enemy3s,player);

		// 플레이어1 가미가제(탄환1)
		intercheck3(bullet1s,player);
		
		// 플레이어1 가미가제(탄환2)
		intercheck3(bullet2s,player);

		// 충돌 체크 (플레이어2의 미사일 충돌)
		score2 += intercheck1(missiles2, stones, 50);

		// 플레이어2미사일과 bullet1의 충돌
		score2 += intercheck1(missiles2, bullet1s ,20);
		

		// 플레이어2의 미사일에 적1 폭발 (3번 맞아야 격추되도록 변경)
		score2 += intercheck2(missiles2, enemy1s ,100,1);
		
		// 플레이어2의 미사일에 적2 폭발
		score2 += intercheck2(missiles2, enemy2s ,100,3);
		
		// 플레이어2 미사일에 적3 폭발
		score2 += intercheck2(missiles2, enemy3s ,100,3);
		

		// 플레이어2 가미가제(운석)
		intercheck3(stones,player2);
		

		// 플레이어2 가미가제(적1)
		intercheck3(enemy1s,player2);
		
		// 플레이어2 가미가제(적2)
		intercheck3(enemy2s,player2);

		// 플레이어2 가미가제(적3)
		intercheck3(enemy3s,player2);
		
		// 플레이어2 가미가제(탄환1)
		intercheck3(bullet1s,player2);

		// 플레이어2 가미가제(탄환2)
		intercheck3(bullet2s,player2);
		

	}

	/**
	 * 돌, 미사일1,2 생성,  적 1,2,3
	 */
	private void makeobjeck() {
		// 1초 마다 한 번씩 Stone 생성
		long currentTime = System.currentTimeMillis();// 현재 시간(1970.2.1
														// 0:0:0 부터 시작)
		if (currentTime - startTime > Timer.bossAppearTime) {

			BGMplayer.stop();
			boss.active = true;
			bossbgmplayer.loop(Clip.LOOP_CONTINUOUSLY);//반복 횟수 지정
			bossbgmplayer.start();
		}

		if (currentTime - prevStoneCreationTime > Timer.stoneCreationSpeed) {
			Stone stone = new Stone(stoneImage);
			stone.active = true;
			stones.add(stone);
			prevStoneCreationTime = currentTime;
		}

		// player1의 슈팅
		if (player.shoot) {
			currentTime = System.currentTimeMillis();// 현재 시간
			if (currentTime - prevFireTime > Timer.fireSpeed) {
				Missile missile = new Missile(missileImage, player.x
						+ player.image.getWidth(null), player.y + 16);
				missile.active = true;
				missiles.add(missile);
				attackplayer.setFramePosition(0);
				attackplayer.start();
				prevFireTime = currentTime;
			}
		}

		// player2의 슈팅
		if (player2.shoot) {
			currentTime = System.currentTimeMillis();// 현재 시간
			if (currentTime - prevFireTime2 > Timer.fireSpeed) {
				Missile missile = new Missile(missileImage2, player2.x
						+ player2.image.getWidth(null), player2.y + 16);
				missile.active = true;
				missiles2.add(missile);
				attackplayer.setFramePosition(0);
				attackplayer.start();
				prevFireTime2 = currentTime;
			}
		}

		// 적1의 출현
		currentTime = System.currentTimeMillis();// 현재 시간
		if ((currentTime - startTime > Timer.enemy1Appear1 && currentTime
				- startTime < Timer.enemy1DisAppear1)
				|| (currentTime - startTime > Timer.enemy1Appear2 && currentTime
						- startTime < Timer.enemy1DisAppear2)
				|| (currentTime - startTime > Timer.enemy1Appear2 && currentTime
						- startTime < Timer.enemy1DisAppear2)
				|| (currentTime - startTime > Timer.enemy1Appear3 && currentTime
						- startTime < Timer.enemy1DisAppear3)
				|| (currentTime - startTime > Timer.enemy1Appear4 && currentTime
						- startTime < Timer.enemy1DisAppear4)
				|| (currentTime - startTime > Timer.enemy1Appear5 && currentTime
						- startTime < Timer.enemy1DisAppear5)
				|| (currentTime - startTime > Timer.enemy1Appear6 && currentTime
						- startTime < Timer.enemy1DisAppear6)) {
			if (currentTime - prevEnemy1CreationTime > Timer.enemy1CreationSpeed) {
				Enemy1 enemy1 = new Enemy1(enemy1Image, player, player2);
				enemy1.active = true;
				// enemy1.active = false;// 테스트 용
				enemy1s.add(enemy1);
				prevEnemy1CreationTime = currentTime;
			}
		}
		// 적2의 출현
		currentTime = System.currentTimeMillis();// 현재 시간
		if ((currentTime - startTime > Timer.enemy2Appear1 && currentTime
				- startTime < Timer.enemy2DisAppear1)
				|| (currentTime - startTime > Timer.enemy2Appear2 && currentTime
						- startTime < Timer.enemy2DisAppear2)
				|| (currentTime - startTime > Timer.enemy2Appear2 && currentTime
						- startTime < Timer.enemy2DisAppear2)
				|| (currentTime - startTime > Timer.enemy2Appear3 && currentTime
						- startTime < Timer.enemy2DisAppear3)
				|| (currentTime - startTime > Timer.enemy2Appear4 && currentTime
						- startTime < Timer.enemy2DisAppear4)
				|| (currentTime - startTime > Timer.enemy2Appear5 && currentTime
						- startTime < Timer.enemy2DisAppear5)
				|| (currentTime - startTime > Timer.enemy2Appear6 && currentTime
						- startTime < Timer.enemy2DisAppear6)) {
			if (currentTime - prevEnemy2CreationTime > Timer.enemy2CreationSpeed) {
				Enemy2 enemy2 = new Enemy2(enemy2Image);
				enemy2.active = true;
				this.enemy2x = enemy2.x;
				this.enemy2y = enemy2.y;
				enemy2s.add(enemy2);
				prevEnemy2CreationTime = currentTime;

				for (int i = enemy2s.size() - 1; i >= 0; i--) {
					if (enemy2s.get(i).active) {
						currentTime = System.currentTimeMillis();// 현재 시간
						if (currentTime -((Enemy2)enemy2s.get(i)).prevBullet1Time > Timer.bullet1Speed) {
							Bullet1 bullet1 = new Bullet1(bullet1Image,
									enemy2s.get(i).x, enemy2s.get(i).y + 16,
									player, player2);
							bullet1.active = true;
							bullet1s.add(bullet1);
							((Enemy2)enemy2s.get(i)).prevBullet1Time = currentTime;
						}
					}
				}
			}
		}
		// 적3의 출현
		currentTime = System.currentTimeMillis();// 현재 시간
		if ((currentTime - startTime > Timer.enemy3Appear1 && currentTime
				- startTime < Timer.enemy3DisAppear1)
				|| (currentTime - startTime > Timer.enemy3Appear2 && currentTime
						- startTime < Timer.enemy3DisAppear2)
				|| (currentTime - startTime > Timer.enemy3Appear2 && currentTime
						- startTime < Timer.enemy3DisAppear2)
				|| (currentTime - startTime > Timer.enemy3Appear3 && currentTime
						- startTime < Timer.enemy3DisAppear3)
				|| (currentTime - startTime > Timer.enemy3Appear4 && currentTime
						- startTime < Timer.enemy3DisAppear4)
				|| (currentTime - startTime > Timer.enemy3Appear5 && currentTime
						- startTime < Timer.enemy3DisAppear5)
				|| (currentTime - startTime > Timer.enemy3Appear6 && currentTime
						- startTime < Timer.enemy3DisAppear6)) {
			if (currentTime - prevEnemy3CreationTime > Timer.enemy3CreationSpeed) {
				Enemy3 enemy3 = new Enemy3(enemy3Image);
				enemy3.active = true;
				this.enemy3x = enemy3.x;
				this.enemy3y = enemy3.y;
				enemy3s.add(enemy3);
				prevEnemy3CreationTime = currentTime;

				for (int i = enemy3s.size() - 1; i >= 0; i--) {
					if (enemy3s.get(i).active) {
						currentTime = System.currentTimeMillis();// 현재 시간
						if (currentTime - ((Enemy3)enemy3s.get(i)).prevBullet2Time > Timer.bullet2Speed) {
							Bullet2 bullet2 = new Bullet2(bullet2Image,
									enemy3s.get(i).x, enemy3s.get(i).y + 16);
							bullet2.active = true;
							bullet2s.add(bullet2);
							((Enemy3)enemy3s.get(i)).prevBullet2Time = currentTime;
						}
					}
				}
			}
		}
		
		if(boss.active){
			currentTime = System.currentTimeMillis();// 현재 시간
			if (currentTime - boss.prevBulletTime > Timer.bossDanMaKuCreationTime) {
				BossDanMaKu1 bossDanMaKu1 = new BossDanMaKu1(bossBulletImage,boss.x, boss.y + 100, 2);
				
				
				int rnd = (int)(Math.random()*2);//랜덤하게 0,1 나오게
				if(rnd == 1){
					bossDanMaKu1.initAimingBullet(boss.x, boss.y, player.x, player.y, 10);//player좌표 찾아 미사일 따라가게 하는 메소드
				}else{
					bossDanMaKu1.initAimingBullet(boss.x, boss.y, player2.x, player2.y, 10);//player좌표 찾아 미사일 따라가게 하는 메소드
				}
				bossDanMaKu1.active = true;
				BossDanMaKu1arr.add(bossDanMaKu1);
				
				boolean odd;
				if((int)(Math.random()*2)==0){
					odd=true;
				}else{odd=false;}
				int dmkNum = 40;
				boss.initCircleBullet(dmkNum, 10,odd);
				for (int i = 0; i < dmkNum; i++) {
					BossDanMaKu2 bossDanMaKu2 = new BossDanMaKu2(
							bossBulletImage2,
							boss.x +210, boss.y + 131, 10,boss.vx[i],boss.vy[i]);
					bossDanMaKu2.active = true;
					BossDanMaKu2arr.add(bossDanMaKu2);
				}
				boss.prevBulletTime = currentTime;
			}
			
		}
		
		
	}
}
